from django.shortcuts import render

# Create your views here.
from django.views import View
from .models import *
from rest_framework.views import APIView
from myapp import myserializers
from rest_framework.response import Response
from utils.captcha.captcha import captcha
from django.http import HttpResponse
import memcache
import requests
import json
from itsdangerous import TimedJSONWebSignatureSerializer as SerializerName
from django.conf import settings
from alipay import AliPay, DCAliPay, ISVAliPay
import os

server = memcache.Client(["39.106.229.25:11211"])

app_private_key_string = open(os.path.join(settings.BASE_DIR, 'utils', 'Key', 'app_private_key.txt')).read()
alipay_public_key_string = open(os.path.join(settings.BASE_DIR, 'utils', 'Key', 'alipay_public_key.txt')).read()

alipay = AliPay(
    appid="2016101800717486",
    app_notify_url='http://127.0.0.1:8000/myapp/alipay_callback/',  # the default notify path
    app_private_key_string=app_private_key_string,
    # alipay public key, do not use your own public key!
    alipay_public_key_string=alipay_public_key_string,
    sign_type="RSA2",  # RSA or RSA2
    debug=False  # False by default.如果是沙箱环境。配置为True
)


class AlipayView(APIView):
    def post(self, request):
        # 如果你是 Python 3的用户，使用默认的字符串即可
        subject = "小米"

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no="4",  # 订单号
            total_amount=10.00,  # 订单售价
            subject=subject,
            return_url="http://127.0.0.1:8000/myapp/alipay_callback/",
            notify_url="http://127.0.0.1:8000/myapp/alipay_callback/"  # 可选, 不填则使用默认notify url
        )

        pay_url = "https://openapi.alipaydev.com/gateway.do?" + order_string

        return Response({
            'code': 200,
            'url': pay_url
        })


class AlipayCallbackView(APIView):
    def get(self, request):
        trade_no = request.GET.get('trade_no')
        out_trade_no = request.GET.get('out_trade_no')
        print(trade_no)
        print(out_trade_no)

        return HttpResponse('Hello World')


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get("username")
        imagecode = request.data.get("imagecode")

        code = server.get(username)

        print(code)

        if imagecode.lower() != code.lower():
            return Response({'code': 500, 'data': '验证码错误'})

        user_ser = myserializers.UserSerializer(data=request.data)
        if user_ser.is_valid():
            user_ser.save()
            return Response({'code': 200, 'data': '创建成功'})
        else:
            return Response({'code': 500, 'data': '创建失败'})


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_ser = User.objects.filter(username=username, password=password).first()
        if user_ser:
            serializer = SerializerName(settings.SECRET_KEY, 360)
            token = serializer.dumps({
                'id': user_ser.id,
                'username': username
            })
            return Response({
                'code': 200,
                'data': '登陆成功',
                'token': token.decode()
            })
        else:
            return Response({
                'code': 500,
                'data': '登陆失败,账号不存在'
            })


class Imges(APIView):  # 验证码
    def get(self, request):
        name, text, image = captcha.generate_captcha()
        response = HttpResponse(image)
        response["Content-Type"] = "image/jpg"
        username = request.GET.get('username')
        server.set(username, text, 60)
        return response


class WeiBoView(APIView):
    def post(self, request):
        token = request.data.get('token')
        params = {
            'client_id': '297351690',
            'client_secret': '8e24e86fd5dfa8d95675316bd969f9f1',
            'grant_type': 'authorization_code',
            'code': token,
            'redirect_uri': 'http://127.0.0.1:8080/weibo_callback'
        }
        url = 'https://api.weibo.com/oauth2/access_token'

        res = requests.post(url, data=params).text
        dict = json.loads(res)
        # print(dict['uid'])
        return Response({
            'code': 200,
            'uid': dict['uid']
        })


class WeiBoBindView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        uid = request.data.get('uid')
        # print(username, password, uid)

        user_yanzheng = User.objects.filter(username=username).first()
        if user_yanzheng:
            if user_yanzheng.password != password:
                return Response({
                    'code': 500,
                    'data': '用户或者密码错误'
                })
        else:
            User.objects.create(username=username, password=password)

        weibo = Weibo.objects.filter(uid=uid).first()
        if weibo:
            return Response({
                'code': 201,
                'data': '用户已绑定过，跳转登陆页面'
            })

        # 微博绑定表的添加
        user = User.objects.filter(username=username).first()
        Weibo.objects.create(uid=uid, user=user)

        return Response({
            'code': 200,
            'data': '绑定成功'
        })


class CateView(APIView):
    def get(self, request):
        uid = request.GET.get('id', 0)
        if uid == 0:
            cate_list = Cate.objects.all()
            cate_ser = myserializers.CateSerializer(instance=cate_list, many=True)
        else:
            cate = Cate.objects.filter(pk=uid).first()
            cate_ser = myserializers.CateSerializer(instance=cate)
        return Response({
            'code': 200,
            'data': cate_ser.data
        })

    def post(self, request):
        uid = request.data.get('id')
        # print(uid)
        if not uid:
            cate_ser = myserializers.CateSerializer(data=request.data)
            if cate_ser.is_valid():
                cate_ser.save()
                return Response({
                    'code': 200,
                    'data': '分类添加成功'
                })
            else:
                print(cate_ser.errors)
                return Response({
                    'code': 500,
                    'data': '分类添加失败'
                })
        else:
            name = request.data.get('newname')
            Cate.objects.filter(pk=uid).update(name=name)
            return Response({
                'code': 200,
                'data': '修改成功'
            })

    def delete(self, request):
        id = request.data.get('cid')
        Cate.objects.filter(pk=id).delete()
        return Response({
            'code': 200,
            'data': '删除成功'
        })


def TokenJie(token):
    serializer = SerializerName(settings.SECRET_KEY, 360)
    try:
        token = serializer.loads(token)
    except Exception as e:
        return None
    return token


class YanzView(APIView):
    def post(self, request):
        token = request.data.get('token')
        tokenyz = TokenJie(token)
        if not tokenyz:
            return Response({
                'code': 404,
                'data': '验证失败'
            })
        return Response({
            'code': 200,
            'data': '验证成功'
        })
